# -*-coding:utf-8 -*- #
# ---------------------------------------------------------------------------
# ProjectName:   selenium_self
# FileName:      db.py
# Author:       test_liu
# Datetime:     2024/10/14 下午8:20
# Description: 数据库连接，并操作
# ---------------------------------------------------------------------------
import pymysql

from WebTest2.WebTest import log
from WebTest2.WebTest.common.read_local_ini import ReadLocalIni


class DB:
    def __init__(self):
        ini = ReadLocalIni()
        host = ini.get_db('host')
        port = ini.get_db('port')
        user = ini.get_db('user')
        password = ini.get_db('password')
        database = ini.get_db('database')
        try:
            self.conn = pymysql.connect(host=host, port=int(port), user=user, password=password, database=database)
            self.cursor = self.conn.cursor()
            print('数据库连接成功')
            log.info('-----数据库连接成功-----')
        except Exception as e:
            log.error(
                f'数据库连接失败，请检查配置文件，连接数据：host={host}, port={port}, user={user}, password={password}, database={database}')
            raise e

    def close(self):
        self.cursor.close()
        self.conn.close()

    def select(self, sql, n=0):
        # 如果有多个结果。默认返回第一个
        # 只返回一个结果
        # 判断sql语句为字符串类型
        if isinstance(sql, str):
            if sql.strip().lower().startswith('select'):
                # 开头判断为select
                try:
                    self.cursor.execute(sql)
                except Exception as e:
                    log.error(f'执行select方法失败，sql语句为{sql}，错误为{e}')
                    raise e
                else:
                    result = self.cursor.fetchall()
                    log.info(f'执行sql成功，sql语句为：{sql}')

                if isinstance(n, int) and result:
                    try:
                        return result[n][0]
                    except Exception as e:
                        log.error(f'执行select方法，获取查询结果失败，传入的n值:{n}，错误为{e}')
                        raise e
            else:
                log.error(f'执行select方法，传入的sql语句不是select语句，sql语句为{sql}')
                raise Exception(f'执行select方法，传入的sql语句不是select语句，sql语句为{sql}')
        else:
            log.error(f'执行select方法，传入的sql语句不是字符串类型，sql语句为{sql}')
            raise Exception(f'执行select方法，传入的sql语句不是字符串类型，sql语句为{sql}')

    def delete(self, sql):
        # 判断sql语句为字符串类型
        if isinstance(sql, str):
            if sql.strip().lower().startswith('delete'):
                # 开头判断为delete
                try:
                    self.cursor.execute(sql)
                    self.conn.commit()
                    log.info(f'执行sql成功，sql语句为：{sql}')
                except Exception as e:
                    log.error(f'执行delete方法失败，sql语句为{sql}，错误为{e}')
                    raise e
            else:
                log.error(f'执行delete方法失败，传入的sql语句不是delete语句，sql语句为{sql}')
                raise Exception(f'执行delete方法失败，传入的sql语句不是delete语句，sql语句为{sql}')
        else:
            log.error(f'执行delete方法失败，传入的sql语句不是字符串类型，sql语句为{sql}')
            raise Exception(f'执行delete方法失败，传入的sql语句不是字符串类型，sql语句为{sql}')